//
//  HomeViewController.m
//  pmmSS
//
//  Created by Mac book on 2017/9/1.
//  Copyright © 2017年 WTFSSD. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeSectionHeaderView.h"
#import "SearchBar.h"
#import "SearchViewController.h"

#import "HomeMenuCell.h"

#import "Home_advertisingCell.h"
#import "HomeshopCell.h"

#import "UIImage+Resize.h"

#import "JFLocation.h"
#import "JFAreaDataManager.h"
#import "JFCityViewController.h"
#import "Commodity_Detail_ViewController.h"

#define KCURRENTCITYINFODEFAULTS [NSUserDefaults standardUserDefaults]

@interface HomeViewController ()<HomeMenuCellDelegate,JFLocationDelegate,JFCityViewControllerDelegate,commodityDataDelegate>

@property(nonatomic,strong)NSArray * categorys;

@property(nonatomic,strong) NSString *shop_index;

/** 选择的结果*/
@property (strong, nonatomic) UILabel *resultLabel;

/** 城市定位管理器*/
@property (nonatomic, strong) JFLocation *locationManager;
/** 城市数据管理器*/
@property (nonatomic, strong) JFAreaDataManager *manager;

@property(nonatomic,strong)NSString *cityName;

@end

@implementation HomeViewController

-(NSArray *)categorys{
    if (!_categorys) {
        _categorys = @[
                       @[@"icon_category_menu_1",
                         @"icon_category_menu_2",
                         @"icon_category_menu_3",
                         @"icon_category_menu_4",
                         @"icon_category_menu_5",
                         @"icon_category_menu_6",
                         @"icon_category_menu_7",
                         @"icon_category_menu_8",
                         @"icon_category_menu_7",
                         @"icon_category_menu_8",
                         @"icon_category_menu_7",
                         @"icon_category_menu_8",
                         ],
                       @[@"钢筋",
                         @"管材",
                         @"油漆",
                         @"工具",
                         @"钢材",
                         @"木材",
                         @"接口",
                         @"五金",
                         @"接口",
                         @"五金",
                         @"接口",
                         @"五金",
                         ]];
    }
    return _categorys;
}



-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

 [self setUpNavBar];

}
- (JFAreaDataManager *)manager {
    if (!_manager) {
        _manager = [JFAreaDataManager shareInstance];
        [_manager areaSqliteDBData];
    }
    return _manager;
}
- (void)viewDidLoad {
    NSLog(@"订单管理界面");
    [super viewDidLoad];



    self.locationManager = [[JFLocation alloc] init];
    _locationManager.delegate = self;
    // Do any additional setup after loading the view.
}

-(void)setUpTableView:(UITableView *)tableView{
    SDCycleScrollView * banner = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, autoScaleH(200)) imageNamesGroup:@[@"demo",@"demo"]];
    tableView.tableHeaderView = banner;

    tableView.sectionFooterHeight = 0.f;
    tableView.sectionHeaderHeight = 0.f;
    tableView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0);

    [tableView registerClass:[HomeMenuCell class] forCellReuseIdentifier:@"HomeMenuCell"];

    [tableView registerClass:[Home_advertisingCell class] forCellReuseIdentifier:@"Home_advertisingCell"];


    [tableView registerClass:[HomeshopCell class] forCellReuseIdentifier:@"HomeshopCell"];
}

-(void)setUpNavBar{


    self.navigationController.navigationBar.translucent = YES;

    [[NSNotificationCenter defaultCenter] postNotificationName:ChangeStatusBarStyleNotificationKey object:nil userInfo:@{@"StatusBarStyle":@(UIStatusBarStyleLightContent)}];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];

    //设置navbaritem

    UIButton *localizeBtn =[HMButton createButtonWithTitle:nil andTitleColor:nil andBgColor:nil andImage:nil andBgImage:nil andSelecter:@selector(clickBarItem) andTarget:self andTag:101];


    localizeBtn.frame = CGRectMake(0, 0, autoScaleW(60), autoScaleW(30));

//
    if (!_cityName) {
     _cityName = @"选择城市";
    }
//
    _resultLabel = [HMLabel createLabelWithText:_cityName andTextColor:[UIColor whiteColor] andBgColor:nil andFont:[UIFont fontWithName:default_fontname size:autoScaleW(12)] andTextAlignment:NSTextAlignmentCenter];
    

   _resultLabel.frame = CGRectMake(0, 0, autoScaleW(50), autoScaleH(30));
    
    [localizeBtn addSubview:_resultLabel];

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(autoScaleW(50), autoScaleH(10), autoScaleW(7), autoScaleH(5))];


    [imageView setImage:[UIImage imageNamed:@"icon_arrow_down_gray"] ];
    [localizeBtn addSubview:imageView];

    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:localizeBtn];

    [self.navigationItem setLeftBarButtonItem:leftItem];


    //--------********----------

    SearchBar * searchBar = [[UINib nibWithNibName:NSStringFromClass([SearchBar class]) bundle:[NSBundle mainBundle]] instantiateWithOwner:nil options:nil].firstObject;
    searchBar.placeholder = @"工型钢工型钢";

    searchBar.editEnable = NO;
    [searchBar addClickTarget:self select:@selector(searchBarClick:)];

    self.navigationItem.titleView = searchBar;

     //--------********----------

    //空白View
    UIView *clearView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 30)];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:clearView];

    self.navigationItem.rightBarButtonItem = rightItem;



}
-(void)searchBarClick:(id)sender{


    SearchViewController *vc = [[SearchViewController alloc]init];

  [self.navigationController pushViewController:vc animated:YES];

}
-(void)clickBarItem{

    NSLog(@"点击了定位");
    JFCityViewController *cityViewController = [[JFCityViewController alloc] init];
    cityViewController.delegate = self;
    cityViewController.title = @"城市";

    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:cityViewController];

    [self presentViewController:navigationController animated:YES completion:nil];

}
#pragma TableView delegate&dataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   // return section == 0?1:10;

    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{


    if (indexPath.section == 0) {
        HomeMenuCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeMenuCell"];
        cell.delegate = self;

        [cell setIcons:self.categorys[0] andTitles:self.categorys[1]];

        return cell;



    }else if (indexPath.section == 1){


        Home_advertisingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Home_advertisingCell"];

        return cell;

    }else if(indexPath.section == 2){
        HomeshopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeshopCell"];

        cell.delegate = self;



        return cell;

    }

    return [[UITableViewCell alloc] init];

}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {

        HomeSectionHeaderView * v = [[HomeSectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, autoScaleH(60))];
        v.title = @"推荐商品";

        return  v;
    }

    return [UIView new];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{




}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{


    return section==1?40:0.1f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

   if (indexPath.section == 1){

     return autoScaleH(116);

    }else if (indexPath.section == 2){

     return autoScaleH(181);

    }

    return autoScaleH(200);

}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat ofsetY = scrollView.contentOffset.y;
    self.navigationController.navigationBar.translucent = ofsetY<200;
    self.navigationController.navigationBar.hidden = ofsetY<-64;
   // NSLog(@"%.f",ofsetY);

    UIImage * bgImage = [UIImage imageWithColor:RGBA(63, 143, 247, ofsetY/150) size:CGSizeMake(SCREEN_WIDTH, 64)];
    [self.navigationController.navigationBar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGFloat ofsetY = scrollView.contentOffset.y;
    self.navigationController.navigationBar.translucent = ofsetY<200;

}

#pragma HomeMenuCellDelegate
-(void)HomeMenuCellDidClick:(NSString *)menu{

    SearchViewController *vc = [[SearchViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];

    NSLog(@"点击菜单:%@",menu);
    
    
}
#pragma mark - commodityDataDelegate  ----- shopId
-(void)clickCollectionItem:(NSString *)shopId{

    NSLog(@"shopId======%@",shopId);

    Commodity_Detail_ViewController  * vc = [[Commodity_Detail_ViewController alloc]init];

    [self.navigationController pushViewController:vc animated:YES];

//    if ([shopId  isEqual: @"0"]) {
//
//
//    }else if ([shopId isEqual:@"1"]){
//
//
//
//    }else if ([shopId isEqual:@"2"]){
//
//
//    }else if ([shopId isEqual:@"3"]){
//
//
//    }

}

#pragma mark - JFCityViewControllerDelegate

- (void)cityName:(NSString *)name {

    NSLog(@"city=====%@",name);

   // _resultLabel.text = name;
    _cityName = name;

     NSLog(@"_cityName.text=====%@",_cityName);
    
}

#pragma mark --- JFLocationDelegate
//定位中...
- (void)locating {
    NSLog(@"定位中...");
}

//定位成功
- (void)currentLocation:(NSDictionary *)locationDictionary {

    NSString *city = [locationDictionary valueForKey:@"City"];
    if (![_resultLabel.text isEqualToString:city]) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"您定位到%@，确定切换城市吗？",city] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            _resultLabel.text = city;
            [KCURRENTCITYINFODEFAULTS setObject:city forKey:@"locationCity"];
            [KCURRENTCITYINFODEFAULTS setObject:city forKey:@"currentCity"];
            [self.manager cityNumberWithCity:city cityNumber:^(NSString *cityNumber) {
                [KCURRENTCITYINFODEFAULTS setObject:cityNumber forKey:@"cityNumber"];
            }];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

/// 拒绝定位
- (void)refuseToUsePositioningSystem:(NSString *)message {
    NSLog(@"%@",message);
}

/// 定位失败
- (void)locateFailure:(NSString *)message {
    NSLog(@"%@",message);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
